package org.example.im.client.console;

import cn.hutool.extra.spring.SpringUtil;
import io.netty.channel.Channel;
import org.example.im.bean.protocol.CommandType;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @author dingrui
 * @since 2022/2/12
 * @description 业务命令集合
 */
@Component
public class ConsoleCommandFactory {

    private static final Map<CommandType, ConsoleCommand> strategyMap = new HashMap<>();

    @PostConstruct
    public void init() {
        Map<String, ConsoleCommand> beansMap = SpringUtil.getBeansOfType(ConsoleCommand.class);
        if (Objects.isNull(beansMap)) return;
        beansMap.values().forEach(o -> {
            strategyMap.put(o.genType(), o);
        });
    }

    public void exec(Scanner s, Channel c) {
        // 指令
        System.out.println("所有指令如下: ");
        Arrays.stream(CommandType.class.getEnumConstants()).forEach(System.out::println);
        System.out.println("输入执行的指令编号: ");
        String command = s.nextLine();
        if (Objects.isNull(command)) return;
        byte commandCode = Byte.parseByte(command);
        CommandType commandType = CommandType.getByCommandCode(commandCode);
        ConsoleCommand strategy = strategyMap.get(commandType);
        if (Objects.isNull(strategy)) {
            System.out.println("[C-Console] 无法识别指令[{" + command + "}] 重新输入");
            return;
        }
        strategy.exec(s, c);
    }
}
